package cn.iocoder.yudao.module.product.evaluation.convert;

import cn.iocoder.yudao.framework.business.evaluation.enums.ScoreLevelEnum;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.api.product.evaluation.dto.ProductEvaluationCreateReqDTO;
import cn.iocoder.yudao.module.api.trade.order.dto.TradeOrderItemRespDTO;
import cn.iocoder.yudao.module.product.evaluation.dal.dataobject.ProductEvaluationDO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 产品评价 Convert
 *
 * @author wangzhs
 */
@Mapper
public interface ProductEvaluationConvert {

    ProductEvaluationConvert INSTANCE = Mappers.getMapper(ProductEvaluationConvert.class);

    default ProductEvaluationDO convert(ProductEvaluationCreateReqDTO createReqVO, TradeOrderItemRespDTO orderItem) {
        ProductEvaluationDO reqVO = BeanUtils.toBean(createReqVO, ProductEvaluationDO.class);
        return toProductCommentDO(reqVO, createReqVO.getDescriptionScores(), createReqVO.getBenefitScores(), orderItem);
    }

    private ProductEvaluationDO toProductCommentDO(ProductEvaluationDO evaluationDO, Integer descriptionScores, Integer benefitScores, TradeOrderItemRespDTO orderItem) {
        evaluationDO.setVisible(true);
        evaluationDO.setAnonymous(false);
        evaluationDO.setScores(convertScores(descriptionScores, benefitScores));
        evaluationDO.setSpuId(orderItem.getId());
        evaluationDO.setSpuName(orderItem.getSpuName());
        evaluationDO.setSkuPicUrl(orderItem.getPicUrl());
        evaluationDO.setSkuProperties(orderItem.getProperties());
        return evaluationDO;
    }

    default Integer convertScores(Integer descriptionScores, Integer benefitScores) {
        if (descriptionScores == null) {
            descriptionScores = ScoreLevelEnum.STAR_5.getValue();
        }
        if (benefitScores == null) {
            benefitScores = ScoreLevelEnum.STAR_5.getValue();
        }
        // 计算评价最终综合评分 最终星数 = （产品评星 + 服务评星） / 2
        BigDecimal sumScore = new BigDecimal(descriptionScores + benefitScores);
        BigDecimal divide = sumScore.divide(BigDecimal.valueOf(2L), 0, RoundingMode.DOWN);
        return divide.intValue();
    }

}
